package com.tim.app.ui.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.TimeUtil;
import com.application.library.widget.RatioImageView;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Dynamic;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ActionResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.ui.adapter.someone_homepage.PriseAvatarAdapter;
import com.tim.app.ui.widget.imagepick.bean.ImageItem;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewActivity;
import com.tim.app.ui.widget.imagepick.ui.ImagePreviewTopicActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;

/**
 * 动态详情的header
 */

public class DynamicHeadView extends RelativeLayout implements View.OnClickListener, LoadMoreHandler {

    public static final String TAG = "DynamicHeadView";

    private ImageView ivPrise;
    private ImageView ivComment;
    private TextView tvDynamicTitle;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvComment;
    private PriseAvatarAdapter adapter;
    private List<String> dataList;
    RoundedImageView rivAvatar;
    TextView tvUserName;
    TextView tvPriseNumber, tvCommentNumber, tvPublishTime;

    private RelativeLayout rlImageContainer;
    private RatioImageView rivDynamicOne;

    private View icContainerTwo;
    private RatioImageView rivDynamicTwo_one;
    private RatioImageView rivDynamicTwo_two;

    private View icContainerThree;
    private RatioImageView rivDynamicThree_one;
    private RatioImageView rivDynamicThree_two;
    private RatioImageView rivDynamicThree_three;

    private View icContainerFour;
    private RatioImageView rivDynamicFour_one;
    private RatioImageView rivDynamicFour_two;
    private RatioImageView rivDynamicFour_three;
    private RatioImageView rivDynamicFour_four;

    private View icContainerFive;
    private RatioImageView rivDynamicFive_one;
    private RatioImageView rivDynamicFive_two;
    private RatioImageView rivDynamicFive_three;
    private RatioImageView rivDynamicFive_four;
    private RatioImageView rivDynamicFive_five;

    private View icContainerSix;
    private RatioImageView rivDynamicSix_one;
    private RatioImageView rivDynamicSix_two;
    private RatioImageView rivDynamicSix_three;
    private RatioImageView rivDynamicSix_four;
    private RatioImageView rivDynamicSix_five;
    private RatioImageView rivDynamicSix_six;

    private Dynamic dynamic;

    Handler mHandler;
    PriseTask priseTask;

    public DynamicHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvPriseNumber = (TextView) findViewById(R.id.tvPriseNumber);
        tvCommentNumber = (TextView) findViewById(R.id.tvCommentNumber);

        tvPublishTime = (TextView) findViewById(R.id.tvPublishTime);
        tvDynamicTitle = (TextView) findViewById(R.id.tvDynamicTitle);
        ivPrise = (ImageView) findViewById(R.id.ivPrise);
        ivComment = (ImageView) findViewById(R.id.ivComment);
        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvComment = (WrapRecyclerView) findViewById(R.id.wrvComment);

        rlImageContainer = (RelativeLayout) findViewById(R.id.rlImageContainer);
        rivDynamicOne = (RatioImageView) findViewById(R.id.icContainerOne);
        rivDynamicOne.setTag(0);
        rivDynamicOne.setOnClickListener(imageOnclickListener);

        icContainerTwo = findViewById(R.id.icContainerTwo);
        rivDynamicTwo_one = (RatioImageView) findViewById(R.id.rivDynamicTwo_one);
        rivDynamicTwo_two = (RatioImageView) findViewById(R.id.rivDynamicTwo_two);
        rivDynamicTwo_one.setTag(0);
        rivDynamicTwo_two.setTag(1);
        rivDynamicTwo_one.setOnClickListener(imageOnclickListener);
        rivDynamicTwo_two.setOnClickListener(imageOnclickListener);

        icContainerThree = findViewById(R.id.icContainerThree);
        rivDynamicThree_one = (RatioImageView) findViewById(R.id.rivDynamicThree_one);
        rivDynamicThree_two = (RatioImageView) findViewById(R.id.rivDynamicThree_two);
        rivDynamicThree_three = (RatioImageView) findViewById(R.id.rivDynamicThree_three);
        rivDynamicThree_one.setTag(0);
        rivDynamicThree_two.setTag(1);
        rivDynamicThree_three.setTag(2);
        rivDynamicThree_one.setOnClickListener(imageOnclickListener);
        rivDynamicThree_two.setOnClickListener(imageOnclickListener);
        rivDynamicThree_three.setOnClickListener(imageOnclickListener);

        icContainerFour = findViewById(R.id.icContainerFour);
        rivDynamicFour_one = (RatioImageView) findViewById(R.id.rivDynamicFour_one);
        rivDynamicFour_two = (RatioImageView) findViewById(R.id.rivDynamicFour_two);
        rivDynamicFour_three = (RatioImageView) findViewById(R.id.rivDynamicFour_three);
        rivDynamicFour_four = (RatioImageView) findViewById(R.id.rivDynamicFour_four);
        rivDynamicFour_one.setTag(0);
        rivDynamicFour_two.setTag(1);
        rivDynamicFour_three.setTag(2);
        rivDynamicFour_four.setTag(3);
        rivDynamicFour_one.setOnClickListener(imageOnclickListener);
        rivDynamicFour_two.setOnClickListener(imageOnclickListener);
        rivDynamicFour_three.setOnClickListener(imageOnclickListener);
        rivDynamicFour_four.setOnClickListener(imageOnclickListener);

        icContainerFive = findViewById(R.id.icContainerFive);
        rivDynamicFive_one = (RatioImageView) findViewById(R.id.rivDynamicFive_one);
        rivDynamicFive_two = (RatioImageView) findViewById(R.id.rivDynamicFive_two);
        rivDynamicFive_three = (RatioImageView) findViewById(R.id.rivDynamicFive_three);
        rivDynamicFive_four = (RatioImageView) findViewById(R.id.rivDynamicFive_four);
        rivDynamicFive_five = (RatioImageView) findViewById(R.id.rivDynamicFive_five);
        rivDynamicFive_one.setTag(0);
        rivDynamicFive_two.setTag(1);
        rivDynamicFive_three.setTag(2);
        rivDynamicFive_four.setTag(3);
        rivDynamicFive_five.setTag(4);
        rivDynamicFive_one.setOnClickListener(imageOnclickListener);
        rivDynamicFive_two.setOnClickListener(imageOnclickListener);
        rivDynamicFive_three.setOnClickListener(imageOnclickListener);
        rivDynamicFive_four.setOnClickListener(imageOnclickListener);
        rivDynamicFive_five.setOnClickListener(imageOnclickListener);


        icContainerSix = findViewById(R.id.icContainerSix);
        rivDynamicSix_one = (RatioImageView) findViewById(R.id.rivDynamicSix_one);
        rivDynamicSix_two = (RatioImageView) findViewById(R.id.rivDynamicSix_two);
        rivDynamicSix_three = (RatioImageView) findViewById(R.id.rivDynamicSix_three);
        rivDynamicSix_four = (RatioImageView) findViewById(R.id.rivDynamicSix_four);
        rivDynamicSix_five = (RatioImageView) findViewById(R.id.rivDynamicSix_five);
        rivDynamicSix_six = (RatioImageView) findViewById(R.id.rivDynamicSix_six);

        rivDynamicSix_one.setTag(0);
        rivDynamicSix_two.setTag(1);
        rivDynamicSix_three.setTag(2);
        rivDynamicSix_four.setTag(3);
        rivDynamicSix_five.setTag(4);
        rivDynamicSix_six.setTag(5);
        rivDynamicOne.setOnClickListener(imageOnclickListener);
        rivDynamicSix_two.setOnClickListener(imageOnclickListener);
        rivDynamicSix_three.setOnClickListener(imageOnclickListener);
        rivDynamicSix_four.setOnClickListener(imageOnclickListener);
        rivDynamicSix_five.setOnClickListener(imageOnclickListener);
        rivDynamicSix_six.setOnClickListener(imageOnclickListener);

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);
        wrvComment.setOverScrollMode(View.OVER_SCROLL_NEVER);

        final GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 9
        );
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (wrvComment.getWarpAdapter().getItemViewType(position) == RecyclerView.INVALID_TYPE || wrvComment.getWarpAdapter().getItemViewType(position) == RecyclerView.INVALID_TYPE - 1) {
                    return layoutManager.getSpanCount();
                }
                return 1;
            }
        });
        wrvComment.setLayoutManager(layoutManager);

        dataList = new ArrayList<>();
        adapter = new PriseAvatarAdapter(getContext(), dataList);
        wrvComment.setAdapter(adapter);
        ivPrise.setOnClickListener(this);
        ivComment.setOnClickListener(this);

        rivAvatar.setOnClickListener(this);
        tvUserName.setOnClickListener(this);

        mHandler = new Handler();
        priseTask = new PriseTask();
    }

    /**
     * 刷新页面
     *
     * @param data
     */
    public void setData(final Dynamic data) {
        if (null == data)
            return;
        this.dynamic = data;
        if (null != dynamic.getUserMsg() && !TextUtils.isEmpty(dynamic.getUserMsg().getUserId())) {
            if (!TextUtils.isEmpty(data.getUserMsg().getName())) {
                tvUserName.setText(data.getUserMsg().getName());
            }
            if (!TextUtils.isEmpty(data.getUserMsg().getImage())) {
                BitmapLoader.ins().loadImage(data.getUserMsg().getImage(), rivAvatar);
            }
        }
        if (!TextUtils.isEmpty(data.getContent())) {
            tvDynamicTitle.setVisibility(View.VISIBLE);
            tvDynamicTitle.setText(data.getContent());
        } else {
            tvDynamicTitle.setVisibility(View.GONE);
        }
        tvPublishTime.setText(TimeUtil.formatTimeRuleOne(getContext(), data.getCreateTime()));
        tvPriseNumber.setText(getResources().getString(R.string.selectPriseNumber, String.valueOf(data.getAgreeCount())));
        tvCommentNumber.setText(getResources().getString(R.string.selectCommentNumber, String.valueOf(data.getCommentCount())));

        if (null != data.getActionStateMsg()) {
            if (null != data.getActionStateMsg().getAgreeState()) {
                ivPrise.setSelected(true);
                initPrise = true;
                isPrise = true;
            } else {
                ivPrise.setSelected(false);
            }
        } else {
            ivPrise.setSelected(false);
        }
        if (null != data.getImageUrl()) {
            if (data.getImageUrl().size() == 0) {
                rlImageContainer.setVisibility(View.GONE);
            } else {
                rlImageContainer.setVisibility(View.VISIBLE);
                if (data.getImageUrl().size() == 1) {
                    rivDynamicOne.setVisibility(View.VISIBLE);
                    icContainerTwo.setVisibility(View.GONE);
                    icContainerThree.setVisibility(View.GONE);
                    icContainerFour.setVisibility(View.GONE);
                    icContainerFive.setVisibility(View.GONE);
                    icContainerSix.setVisibility(View.GONE);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(0), rivDynamicOne);
                } else if (data.getImageUrl().size() == 2) {
                    rivDynamicOne.setVisibility(View.GONE);
                    icContainerTwo.setVisibility(View.VISIBLE);
                    icContainerThree.setVisibility(View.GONE);
                    icContainerFour.setVisibility(View.GONE);
                    icContainerFive.setVisibility(View.GONE);
                    icContainerSix.setVisibility(View.GONE);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(0), rivDynamicTwo_one);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(1), rivDynamicTwo_two);
                } else if (data.getImageUrl().size() == 3) {
                    rivDynamicOne.setVisibility(View.GONE);
                    icContainerTwo.setVisibility(View.GONE);
                    icContainerThree.setVisibility(View.VISIBLE);
                    icContainerFour.setVisibility(View.GONE);
                    icContainerFive.setVisibility(View.GONE);
                    icContainerSix.setVisibility(View.GONE);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(0), rivDynamicThree_one);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(1), rivDynamicThree_two);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(2), rivDynamicThree_three);
                } else if (data.getImageUrl().size() == 4) {
                    rivDynamicOne.setVisibility(View.GONE);
                    icContainerTwo.setVisibility(View.GONE);
                    icContainerThree.setVisibility(View.GONE);
                    icContainerFour.setVisibility(View.VISIBLE);
                    icContainerFive.setVisibility(View.GONE);
                    icContainerSix.setVisibility(View.GONE);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(0), rivDynamicFour_one);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(1), rivDynamicFour_two);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(2), rivDynamicFour_three);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(3), rivDynamicFour_four);
                } else if (data.getImageUrl().size() == 5) {
                    rivDynamicOne.setVisibility(View.GONE);
                    icContainerTwo.setVisibility(View.GONE);
                    icContainerThree.setVisibility(View.GONE);
                    icContainerFour.setVisibility(View.VISIBLE);
                    icContainerFive.setVisibility(View.VISIBLE);
                    icContainerSix.setVisibility(View.GONE);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(0), rivDynamicFive_one);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(1), rivDynamicFive_two);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(2), rivDynamicFive_three);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(3), rivDynamicFive_four);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(4), rivDynamicFive_five);
                } else if (data.getImageUrl().size() == 6) {
                    rivDynamicOne.setVisibility(View.GONE);
                    icContainerTwo.setVisibility(View.GONE);
                    icContainerThree.setVisibility(View.GONE);
                    icContainerFour.setVisibility(View.GONE);
                    icContainerFive.setVisibility(View.GONE);
                    icContainerSix.setVisibility(View.VISIBLE);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(0), rivDynamicSix_one);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(1), rivDynamicSix_two);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(2), rivDynamicSix_three);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(3), rivDynamicSix_four);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(4), rivDynamicSix_five);
                    BitmapLoader.ins().loadImage(data.getImageUrl().get(5), rivDynamicSix_six);
                }
            }
        } else {
            rlImageContainer.setVisibility(View.GONE);
        }
    }

    /**
     * 更新评论数量
     */
    public void updateDyanmicCommentCount(Dynamic dynamic) {
        if (null == dynamic) {
            return;
        }
        this.dynamic = dynamic;
        tvCommentNumber.setText(getResources().getString(R.string.selectCommentNumber, String.valueOf(dynamic.getCommentCount())));
    }

    View.OnClickListener imageOnclickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            List<String> list = dynamic.getImageUrl();
            ArrayList<ImageItem> images = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                ImageItem imageItem = new ImageItem();
                imageItem.url = list.get(i);
                imageItem.isFromNet = true;
                images.add(imageItem);
            }
            Intent intent = new Intent(getContext(), ImagePreviewTopicActivity.class);
            intent.putExtra(ImagePickerManager.EXTRA_SELECTED_IMAGE_POSITION, position);
            intent.putExtra(ImagePickerManager.EXTRA_IMAGE_ITEMS, images);
            intent.putExtra(ImagePreviewActivity.ISORIGIN, false);
            getContext().startActivity(intent);  //如果是多选，点击图片进入预览界面

        }
    };

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivPrise:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                isPrise = !isPrise;
                ivPrise.setSelected(isPrise);
                if (isPrise) {
                    dynamic.setAgreeCount(dynamic.getAgreeCount() + 1);
                } else {
                    dynamic.setAgreeCount(dynamic.getAgreeCount() - 1);
                }
                tvPriseNumber.setText(getResources().getString(R.string.selectPriseNumber, String.valueOf(dynamic.getAgreeCount())));
                mHandler.removeCallbacks(priseTask);
                mHandler.postDelayed(priseTask, AppKey.CLICK_REPEAT_TIME);
                break;
            case R.id.rivAvatar:
            case R.id.tvUserName:
            case R.id.tvSignature:
                SomeoneHomepageActivity.start(getContext(), dynamic.getUserMsg(), false);
                break;
            case R.id.ivComment:
                EventManager.ins().sendEvent(EventTag.DO_SHOW_KEYBOARD, 0, 0, null);
                break;
        }
    }

    boolean isPrise;
    boolean initPrise;

    /**
     * 赞任务
     */
    class PriseTask implements Runnable {

        @Override
        public void run() {
            if (initPrise != isPrise) {
                addPriseOrCancelPrise();
            }
        }
    }

    /**
     * 赞/取消赞
     */
    public void addPriseOrCancelPrise() {
        API_User.ins().addPrise(TAG, UserManager.ins().getUserId(), AppKey.TYPE_DYNAMIC, dynamic.getId(), AppKey.AGREE, dynamic.getUserMsg().getUserId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    ActionResult result = new Gson().fromJson(resultValue, ActionResult.class);
                    if (null != result && null != result.getRes()) {
                        if (null == dynamic.getActionStateMsg()) {
                            dynamic.setActionStateMsg(new ActionStateMsg());
                        }
                        dynamic.getActionStateMsg().setAgreeState(result.getRes().getAction().getId());
                    }
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


}
